using System;
using System.Collections.Generic;

namespace GameKit.Core.Context
{
    /// <summary>
    /// 系统/控制器Context
    /// </summary>
    public class SystemContext : Context, ISystemContext
    {
        private readonly Dictionary<Type, ISystem> _systemMap = new();
        private readonly List<ISystem> _systemList = new();

        public SystemContext(string name) : base(name)
        {
        }

        public T AddSystem<T>() where T : ISystem
        {
            return Activator.CreateInstance<T>();
        }

        public T AddSystem<T>(T system) where T : ISystem
        {
            _systemList.Add(system);
            _systemMap[system.GetType()] = system;
            return system;
        }

        public T GetSystem<T>() where T : ISystem
        {
            if (_systemMap.TryGetValue(typeof(T), out var system))
            {
                return (T)system;
            }

            return default;
        }

        public void OnUpdate(float deltaTime)
        {
            for (var i = 0; i < _systemList.Count; i++)
            {
                _systemList[i].OnUpdate(deltaTime);
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            for (int i = _systemList.Count - 1; i >= 0; i--)
                _systemList[i].OnDestroy();

            _systemList.Clear();
        }
    }
}